package cn.satoken.config;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.serializer.impl.SaSerializerTemplateForJdkUseBase64;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.strategy.SaStrategy;
import cn.satoken.util.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;

/**
 * <h3>saToken</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-02-07 10:07:25
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Value("${swaggerstatus:true}")
    private boolean status;

    @PostConstruct
    public void rewriteComponent() {
        // 设置序列化方案: JDK序列化 + Base64
        SaManager.setSaSerializerTemplate(new SaSerializerTemplateForJdkUseBase64());
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handler -> {
            // ✅ 1. 放行 OPTIONS 预检请求
            SaRouter.match(SaHttpMethod.OPTIONS)
                    .free(r -> System.out.println("--------OPTIONS预检请求，不做处理"))
                    .back();  // 🔥 立刻中断，不走后续逻辑

            // ✅ 2. 登录校验逻辑（非预检请求）
            if (status) {
                SaRouter.match("/**")
                        .notMatch(
                                "/user/login",
                                "/api/captcha",
                                "/v3/**",
                                "/swagger-resources",
                                "/webjars/**",
                                "/favicon.ico",
                                "/doc.html"
                        )
                        .check(r -> StpUtil.checkLogin());
            } else {
                SaRouter.match("/**")
                        .notMatch("/user/login", "/api/captcha")
                        .check(r -> StpUtil.checkLogin());
            }
        })).addPathPatterns("/**");
    }
    //配置跨域请求
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*") //指定跨域地址  .allowedOrigins("http://localhost:3000", "https://yourdomain.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
    /**
     * 重写Sa-Token框架内部算法策略
     */
    @PostConstruct
    public void rewiteSaStrategy(){
        // 重写 Token 生成策略
        SaStrategy.instance.createToken = (loginId, loginType) -> {
            return JwtUtil.createJWT(loginId.toString());    // 随机60位长度字符串
        };
    }
}
